<template>
  <div class="product-sku" :key="componentKey">
    <div class="flex items-center">
      <button @click="refreshPage" class="text-sm text-gray-500 flex items-center px-1.5">
        <span
          class="i-codicon-debug-restart text-sm text-icon text-gray-500 m-auto"
        ></span>
        更新数据
      </button>
      <button @click="" class="text-sm text-gray-500 flex items-center px-1.5">
        <span
          class="i-codicon-debug-restart text-sm text-icon text-gray-500 m-auto"
        ></span>
        测试数据
      </button>
    </div>
    <div><h3>{{ props.product?.name }}</h3></div>

    <!-- 商品主图 -->
    <div class="main-image">
      <img
        :src="currentSku.image || product?.defaultImage"
        style="max-width: 320px; max-height: 360px"
      />
    </div>

    <p class="text-white">当前选择的SKU：{{ currentSku }}</p>

    <p class="text-white">选择的规格： {{ selectedSpecs }}</p>

    <!-- 规格选择器 -->
    <div class="spec-selector" v-for="spec in product?.specs" :key="spec.name">
      <h3>{{ spec.name }}</h3>
      <div class="spec-options">
        <el-tag
          v-for="value in spec.values"
          :key="value"
          :type="isSpecSelected(spec.name, value) ? 'primary' : 'info'"
          @click="selectSpec(spec.name, value)"
          :disabled="!availableSpecs(spec.name, value)"
        >
          {{ value }}
        </el-tag>
      </div>
    </div>
    <!-- 价格库存显示 -->
    <div class="price-stock">
      <span class="price">¥{{ currentSku.price || product?.priceRange.join("-")  }}</span>
      <span class="stock" v-if="currentSku.stock !== undefined">
        库存: {{ currentSku.stock }}件
      </span>
    </div>

    <!-- 购买按钮 -->
    <el-button type="danger" :disabled="!canAddToCart" @click="addToCart">
      {{ buttonText }}
    </el-button>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, watchEffect, onMounted } from "vue";
import type { ProductInfo,Sku } from "@/api/types/product";
// 定义规格选择对象的类型
type SelectedSpecs = {
  [key: string]: any; // 或更具体的类型如 string
};

const props = defineProps<{
  product: ProductInfo | null; // 允许接收null
}>();

const emptySku: Sku = {
  id: "",
  specs: {},
  price: 0,
  stock: 0,
  image: "",
  originalPrice: 0,
};
// 当前选择的规格组合
const selectedSpecs = ref<SelectedSpecs>({});

// 计算当前SKU
const currentSku = computed<Sku>(() => {
  // 使用可选链确保安全访问
  const foundSku = props.product?.skus?.find((sku) =>
    Object.entries(selectedSpecs.value).every(
      ([specName, specValue]) => sku.specs[specName] === specValue
    )
  );
  return foundSku || emptySku;
});
// 提前计算所有有效规格组合
const validCombinations = computed(() => {
  return props.product?.skus?.map((sku) => sku.specs) || [];
});

// 使用备忘录优化规格可用性检查
const availableSpecs = computed(() => {
  const cache = new Map<string, boolean>();
  return (specName: string, specValue: string) => {
    const key = `${specName}-${specValue}-${JSON.stringify(selectedSpecs.value)}`;
    if (!cache.has(key)) {
      const tempSpecs = { ...selectedSpecs.value, [specName]: specValue };
      cache.set(
        key,
        props.product?.skus?.some((sku) =>
          Object.entries(tempSpecs).every(([n, v]) => sku.specs[n] === v)
        ) ?? false
      );
    }
    return cache.get(key)!;
  };
});

const initDefaultSelection = () => {
  if (!props.product?.specs) return;

  // 创建临时对象避免重复触发响应式更新
  const newSelectedSpecs: Record<string, string> = {};

  props.product.specs.forEach((spec) => {
    // 找出第一个有库存的规格值
    const availableValue = spec.values.find((value) => {
      const tempSpecs = { ...newSelectedSpecs, [spec.name]: value };
      return props.product?.skus?.some((sku) =>
        Object.entries(tempSpecs).every(
          ([name, val]) => sku.specs[name] === val && sku.stock > 0
        )
      );
    });

    if (availableValue) {
      newSelectedSpecs[spec.name] = availableValue;
    }
  });
  console.log(newSelectedSpecs);
  // 一次性更新响应式变量
  selectedSpecs.value = newSelectedSpecs;
};
// 选择规格
const selectSpec = (specName: string, specValue: string) => {
  if (isSpecSelected(specName, specValue)) {
    delete selectedSpecs.value[specName];
  } else {
    selectedSpecs.value[specName] = specValue;
  }
};

// 检查规格是否已选
const isSpecSelected = (specName: string, specValue: string) => {
  return selectedSpecs.value[specName] === specValue;
};

// 购买按钮状态
const canAddToCart = computed(() => {
  return (
    currentSku.value.stock > 0 &&
    Object.keys(selectedSpecs.value).length === props.product?.specs.length
  );
});

const buttonText = computed(() => {
  if (!canAddToCart.value) return "请选择规格";
  return currentSku.value.stock > 0 ? "加入购物车" : "已售罄";
});

const addToCart = () => {
  console.log("添加SKU到购物车:", currentSku.value);
  // 调用购物车API...
};
const componentKey = ref(0);
const refreshPage = () => {
  componentKey.value++;
  // 重置数据
  selectedSpecs.value = {};
};

/** 
   * 自动选择第一个可用规格组合，有两个方案
   * 方案一：
   * > 需要严格保证默认选择都有库存
   * > 规格之间存在复杂依赖关系
   * > SKU数量较少（<50个）
   * 
   * 方案二：
   * > 商品SKU数量较多（>50个）
   * > 希望优先展示有库存的完整组合
   * > 可以接受部分规格可能无库存（需UI标注）
 */
onMounted(() => {
  // 方案一
  // initDefaultSelection();
});
watch(() => props.product, initDefaultSelection, { immediate: true });
// 在computed或独立函数中实现
const getDefaultSelection = (product: ProductInfo) => {
  console.log("自动选择第一个可用规格组合");
  const defaultSpecs: Record<string, string> = {};
  if (!product?.specs) return defaultSpecs;

  // 优先选择有库存的SKU对应规格
  const availableSku = product.skus.find((sku) => sku.stock > 0);
  if (availableSku) {
    product.specs.forEach((spec) => {
      const skuValue = availableSku.specs[spec.name];
      if (spec.values.includes(skuValue)) {
        defaultSpecs[spec.name] = skuValue;
        return;
      }
    });
  }

  // 补充未匹配到的规格
  product.specs.forEach((spec) => {
    if (!defaultSpecs[spec.name]) {
      const firstValid = spec.values.find((value) => {
        const testSpecs = { ...defaultSpecs, [spec.name]: value };
        return product.skus.some((sku) =>
          Object.entries(testSpecs).every(([n, v]) => sku.specs[n] === v)
        );
      });
      if (firstValid) defaultSpecs[spec.name] = firstValid;
    }
  });

  return defaultSpecs;
};

//   方案二
watchEffect(() => {
  if (props.product) {
    selectedSpecs.value = getDefaultSelection(props.product);
  }
});
</script>
<style scoped>
.product-sku {
  max-width: 600px;
  padding: 20px;
}

.main-image img {
  width: 100%;
  border: 1px solid #eee;
  margin-bottom: 20px;
}

.spec-selector {
  margin-bottom: 20px;
}

.spec-selector h3 {
  margin-bottom: 10px;
  font-size: 16px;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spec-options .el-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.price-stock {
  margin: 20px 0;
  font-size: 18px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin-right: 15px;
}

.stock {
  color: #666;
}
</style>
